#include<string>
#include<vector>
#include<array>
#include<unordered_map>
#include<algorithm>
#include<limits>
#include <stack>
#include<iostream>
#include<sstream>
#include<deque>
#include <queue>
#define MOD 1000000007

class Solution
{
public:
    std::vector<int> loudAndRich(std::vector<std::vector<int>>& richer, std::vector<int>& quiet)
    {
        int n = quiet.size();
        std::vector<std::vector<int>> tu(n);
        std::vector<int> du(n, 0);
        for (const auto& v : richer)
        {
            tu[v[0]].push_back(v[1]);
            du[v[1]]++;
        }

        std::queue<int> q;
        std::vector<int> res(n);
        for (int i = 0; i < n; i++)
        {
            res[i] = i;
            if (du[i] == 0) q.push(i);
        }

        while (!q.empty())
        {
            int index = q.front();
            q.pop();
            for (const auto& v : tu[index])
            {
                if (quiet[res[index]] < quiet[res[v]])
                {
                    res[v] = res[index];
                }
                du[v]--;
                if (du[v] == 0) q.push(v);
            }
        }
        return res;
    }
};
